package com.example.bee_work_3.fragment.system;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.bee_work_3.*;
import com.example.bee_work_3.fragment.ListItem;
import com.example.bee_work_3.net_request.MyJsonArray;
import com.example.bee_work_3.net_request.MyJsonObject;
import com.example.bee_work_3.net_request.WS;
import com.example.bee_work_3.webc_ontent.WebActivity;

import java.util.ArrayList;
import java.util.List;

public class Fragment_System extends Fragment {

    static int pager = 0;
    private int id = 0;
    private int lastItem;

    private List<String[]> mList = new ArrayList<>();
    private List<Integer[]> mIdList = new ArrayList<>();
    private List<ListItem> mDataList = new ArrayList<>();
    private SystemListAdapter systemListAdapter;
    private DataItemAdapter dataListAdapter;

    private SwipeRefreshLayout refreshLayout;
    private RecyclerView classList;
    private ListView dataList;

    private ClassCallBack classCallBack = new ClassCallBack() {
        @Override
        public void onDataChange(int position, int position1) {
            pager = 0;
            mDataList.clear();
            id = mIdList.get(position)[position1];
            getData();
        }
    };

    @Override
    public void onCreate(Bundle save) {
        super.onCreate(save);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStace) {
        View view = inflater.inflate(R.layout.fragment_system, null);
        init(view);
        return view;
    }

    public void init(View view) {
        refreshLayout = view.findViewById(R.id.data_list_refresh);
        classList = view.findViewById(R.id.recycler_class);
        dataList = view.findViewById(R.id.list_data);
        refreshLayout.setColorSchemeColors(Color.GREEN, Color.BLUE, Color.YELLOW);
        refreshLayout.setRefreshing(true);
        dataListAdapter = new DataItemAdapter(getActivity(), R.layout.data_item, mDataList);
        systemListAdapter = new SystemListAdapter(getActivity(), R.layout.class_list, mList, classCallBack);
        //LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //GridLayoutManager layoutManager1 = new GridLayoutManager(getActivity(),4);
        //layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        StaggeredGridLayoutManager layoutManager2 = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL);
        layoutManager2.setOrientation(StaggeredGridLayoutManager.HORIZONTAL);
        classList.setLayoutManager(layoutManager2);
        dataList.setAdapter(dataListAdapter);
        dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListItem item = mDataList.get(position);
                Intent intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("title", item.getText());
                intent.putExtra("URL", item.getLink());
                intent.putExtra("id", item.getId());
                startActivity(intent);
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            dataList.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if (scrollState == SCROLL_STATE_IDLE && lastItem == dataList.getCount() - 1) {
                        getData();
                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    lastItem = dataList.getLastVisiblePosition();
                }
            });
        }
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        pager = 0;
                        mDataList.clear();
                        mList.clear();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                initClassList();
                            }
                        });
                    }
                }).start();
            }
        });
        initClassList();
    }

    public void initClassList() {
        WS.CallBack callBack = new WS.CallBack() {
            @Override
            public void onResult(String Json) {
                MyJsonObject object = new MyJsonObject(Json);
                refreshLayout.setRefreshing(false);
                if (object.getInt("errorCode") != 0) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "加载出错", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                MyJsonArray objectList = object.getJsonArray("data");
                List<MyJsonObject> list = objectList.getList();
                for (MyJsonObject temp : list) {
                    MyJsonArray tmp = temp.getJsonArray("children");
                    List<String> name = new ArrayList<>();
                    List<Integer> id = new ArrayList<>();
                    name.add(temp.getString("name"));
                    id.add(temp.getInt("id"));
                    List<MyJsonObject> list1 = tmp.getList();
                    for (MyJsonObject t : list1) {
                        name.add(t.getString("name"));
                        id.add(t.getInt("id"));
                    }
                    String[] n = name.toArray(new String[0]);
                    mList.add(name.toArray(new String[0]));
                    mIdList.add(id.toArray(new Integer[0]));
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //getData(Integer.parseInt(String.valueOf(mIdList.get(0)[1])));
                        classList.setAdapter(systemListAdapter);
                        id = mIdList.get(0)[0];
                        getData();
                    }
                });
            }
        };
        WS.load("https://www.wanandroid.com/tree/json")
                .addCallBack(callBack)
                .get();
    }

    public void getData() {
        WS.CallBack callBack = new WS.CallBack() {
            @Override
            public void onResult(String Json) {
                final MyJsonObject object = new MyJsonObject(Json);
                if (object.getInt("errorCode") != 0) {
                    if (pager > 0)
                        pager--;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "加载出错", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                MyJsonArray objectList = object.getJsonObject("data").getJsonArray("datas");
                for (MyJsonObject temp : objectList.getList()) {
                    ListItem t = new ListItem(temp.getString("title") + "\n\t\t" + temp.getString("niceDate")
                            , null, temp.getString("link"),temp.getString("niceDate"),
                            temp.getString("author"),temp.getBoolean("collect"),temp.getInt("id"));
                    mDataList.add(t);
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (object.getJsonObject("data").getString("total").equals(mDataList.size() + ""))
                            Toast.makeText(getActivity(), "已加载所有数据", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(getActivity(), "加载成功...", Toast.LENGTH_SHORT).show();
                        dataListAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        WS.load("https://www.wanandroid.com/article/list/" + (pager++) + "/json?cid=" + id)
                .addCallBack(callBack)
                .get();
    }

    interface ClassCallBack {
        void onDataChange(int position, int position1);
    }
}
